<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>three.js examples</title>
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <script src="js/jquery-3.5.1.min.js"></script>
    <script src="js/lhgdialog/lhgcore.lhgdialog.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenMax.min.js"></script>
</head>
<style>


</style>
<body style="margin: 0">

<div class="Mbox"></div>

<div style="position: absolute;top: 0px; left: 0px" id="stat"></div>

<!--<div style="position: absolute; color: #d9edf7  ; top: 120px;">-->
<!--    选中着色器-->
<!--    <div class="color" style="background:#AA4631 " ></div>-->
<!--    <div class="color" style="background:#130AF2 " ></div>-->
<!--    <div class="color" style="background:#C5B49A " ></div>-->
<!--    <div class="color" style="background:#6A5ACD " ></div>-->
<!--    <div class="color" style="background:#E8C279 " ></div>-->
<!--</div>-->


<script type="x-shader/x-vertex" id="vertexshader">

			uniform float amplitude;

			attribute vec3 displacement;
			attribute vec3 customColor;

			varying vec3 vColor;

			void main() {

				vec3 newPosition = position + amplitude * displacement;

				vColor = customColor;

				gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );

			}

		</script>

<script type="x-shader/x-fragment" id="fragmentshader">

			uniform vec3 color;
			uniform float opacity;

			varying vec3 vColor;

			void main() {

				gl_FragColor = vec4( vColor * color, opacity );

			}

		</script>
<style>
    .color{
        background: #130AF2;
        width: 30px;
        height: 30px;
        border-radius: 4px;
        margin: 10px;
    }
</style>

<script language="JavaScript">
    // 参数接收
    function GetArgsFromHref(keys='')
    {
        let urlinfo=window.location.href; //获取当前页面的url
        let len=urlinfo.length;//获取url的长度
        let offset=urlinfo.indexOf("?");//设置参数字符串开始的位置
        let newsidinfo=urlinfo.substr(offset+1,len)//取出参数字符串 这里会获得类似“id=1”这样的字符串
        let newsids=newsidinfo.split("&");//对获得的参数字符串按照“=”进行分割


        let newArr = {}
        let kv = ''
        for(let i=0;i<newsids.length;i++){
            kv = newsids[i].split("=")
            newArr[kv[0]]=kv[1]

        }
        if(keys && newArr[keys] ){
            return newArr[keys]
        }else{
            return  ""
        }

    }
    // 文件目录  lot&filename=LOT9-a-土建.gltf
    let gltfpath = GetArgsFromHref("path") ? "./gltf/"+GetArgsFromHref("path")+"/":"./gltf/lot/"
    let gltfurl =decodeURI(GetArgsFromHref("filename"))
    gltfurl=gltfurl?gltfurl:"LOT9-a-土建.gltf"

    console.log(3333333333)
    console.log(gltfurl)
</script>

<script type="module">
    // 加载主要js

    import * as THREE from './build/three.module.js';
    // 加载内存仪表盘
    import Stats from './threejs/jsm/libs/stats.module.js';
    // 制作一个地板
    let textMesh2,textMesh
    import { MapControls } from './threejs/jsm/controls/OrbitControls.js';
    import {
        PlaneGeometry,
        MeshPhongMaterial,
        Mesh
    } from './build/three.module.js';
    import { OrbitControls } from './threejs/jsm/controls/OrbitControls.js';
    import { GLTFLoader } from './threejs/jsm/loaders/GLTFLoader.js';
    import { EffectComposer } from './threejs/jsm/postprocessing/EffectComposer.js';
    import { RenderPass  } from './threejs/jsm/postprocessing/RenderPass.js';
    import { OutlinePass  } from './threejs/jsm/postprocessing/OutlinePass.js';
    //说色工具  发光体
    import { ToonShader1, ToonShader2, ToonShaderHatching, ToonShaderDotted } from './threejs/jsm/shaders/ToonShader.js';

    // 动态仪表盘
    import { GUI } from './threejs/jsm/libs/dat.gui.module.js';



    import {
        DirectionalLight,
        PMREMGenerator,
        DirectionalLightHelper,
        HemisphereLight,
        HemisphereLightHelper
    } from './build/three.module.js';
    import { CSS2DRenderer, CSS2DObject } from './threejs/jsm/renderers/CSS2DRenderer.js';
    import { CSS3DRenderer, CSS3DObject } from './threejs/jsm/renderers/CSS3DRenderer.js';
    let jsondata= {}
    let isphone =false
        let centetposition;
    let modelSize
    if(GetArgsFromHref("json")){
        $.ajaxSettings.async = false;
        $.getJSON(gltfpath+GetArgsFromHref("json")+".json",function(jsonObj){
            jsondata = jsonObj
        })
    }

    let pmremGenerator;
    // 当前选中颜色index
    let colorIndex =0

    // 模型的三维坐标
    let modelBox
    // 模型的 长宽高  暂时用  x y z 表示
    let modelX ,modelY,modelZ;
    // 颜色数组
    let colorArr =["#AA4631","#130AF2","#C5B49A","#6A5ACD","#E8C279"]
    //点击部件时候 存储旧样式  方便还原
    let oldSelect,oldMaterial;
    // 摄像机 位置
    let cameraPosition={x:100,y:100,z:100}

    let
        // 摄像头
        camera,
        // 场景
        scene,
        // 仪表盘
        gui,
        // 渲染器
        renderer,
        // 地板
        floor,
        // 灯光
        directionalLight,
        // 构件对象
        gltfobj,
        // 摄像旋转控制
        controls,
        // 内存显示器
        stats,
        outlinePass,
        curefont,
        // 特殊效果
        composerAll;



    $(async function(){
        // 初始化
        await init();
        //doinitLight()


        // 灯光
        dolight()
        // dodiban()
        // 渲染
        // doAxsHelper()
        addAxesHelper()
        console.log("当前摄像头位置")
        console.log(camera.position)
        console.log("当前场景位置")
        console.log(scene.position)

    })


    let planeGroup =[]
    let labelRenderer

     let  cando  =false

    function createText(obj,location){


        const earthDiv = document.createElement( 'div' );
        earthDiv.className = 'label';
        earthDiv.textContent = "第三方金黃色的積分換";
        earthDiv.style.marginTop = '';
        earthDiv.style.fontSize = '2em';
        earthDiv.style.background = '#ffffff';
        earthDiv.style.color = '#f60';
        const earthLabel = new CSS3DObject( earthDiv );
        earthLabel.position.copy(location );
        earthLabel.position.x+=0.1

        const geometryx = new THREE.BoxBufferGeometry(40000, 40000, 40000 );
        const materialx = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
        const meshx = new THREE.Mesh( geometryx, materialx );
        meshx.position .copy(location);
        meshx.position.x+=0.1
        meshx.add(earthLabel)


        cando=true

        scene.add(meshx)
        console.log("2222222xxxxxxxxxx")
        console.log(location)
        labelRenderer.render( scene, camera );
        console.log("22222222xxxxxxxxxx")
        controls.addEventListener( 'change', changexxx ); // use if there is no animation loop
        return
        const loader = new THREE.FontLoader();
        loader.load( 'threejs/fonts/siyuans.json', function ( font ) {
            curefont = font
            console.log("curefont")
            console.log(modelSize/20)
            const textGeo = new THREE.TextBufferGeometry(codeText, {
                font: curefont,
                size: modelSize/20,
                height: 122,
                curveSegments:122

            } );
            const textMaterial = new THREE.MeshBasicMaterial( { color: 0x000000} );
            textMesh = new THREE.Mesh(textGeo,textMaterial);
            textMesh.position.copy(location );
            textMesh.position.x+=0.1
            textMesh.rotation.copy(camera.rotation)
            textGroup.push(textMesh)
            scene.add( textMesh );
           let url = changeCanvas()


            console.log("333333333333333333311111111111")
            console.log(codeText.length*modelSize/20)
            console.log(modelSize/20)
            let geometry1 = new THREE.PlaneGeometry(codeText.length*modelSize/20, modelSize/20)
            let texture = THREE.ImageUtils.loadTexture(url, null, function (t) {})

            let material1 = new THREE.MeshBasicMaterial({
                map: texture,
                side: THREE.DoubleSide,
                opacity: 1,
                transparent: true,
            })

            let rect = new THREE.Mesh(geometry1, material1)
            rect.position.copy(location );
            rect.position.x+=0.1
            rect.rotation.copy(camera.rotation)
            scene.add(rect)
            planeGroup.push(rect)

          //
          //
          //   var material = new THREE.MeshBasicMaterial({
          //       map: texture
          //   });
          // let   geometry = new THREE.PlaneGeometry(codeText.length * modelSize/20,  modelSize/20,codeText.length *   modelSize/20);
          //   geometry.faces[0].color.set(0xffffff)
          //   console.log(geometry.position)
          // let   mesh = new THREE.Mesh(geometry, material);
          //   mesh.position.copy(location)
          //   mesh.position.x+=0.1
          //   mesh.rotation.copy(camera.rotation)
          //   scene.add(mesh);


            controls.update()


        } );


    }
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

    function changeCanvas() {
        canvas.width = 25308
        canvas.height = 2812
        //制作矩形
        ctx.fillStyle = "rgba(255,165,0,1)";
        ctx.fillRect(0, 0,  canvas.width , canvas.height)
        ctx.fillStyle = "#000000";
        ctx.font = 'normal '+canvas.width/20+'pt "楷体"'
        ctx.fillText('模型介绍', 100, 20)
        let textWord = '该模型由小少小同学制作完成'
        //文字换行
        let len = parseInt(textWord.length / 10)
        for (let i = 0; i < (len + 1); i++) {
            let space = 10
            if (i === len) {
                space = textWord.length - len * 10
            }
            console.log('len+' + len, 'space+' + space)
            let word = textWord.substr(i * 10, space)
            ctx.fillText(word, canvas.width/50, canvas.width/50*(i+1))
        }
        return  canvas.toDataURL('image/png');
    }




    // 染色切换
    $(function(){

        $(".color").click(function(){

            colorIndex=$(this).index()
        })

    })
    // // 初始化灯光
    // function doinitLight() {
    // 	var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.3 );//模拟远处类似太阳的光源
    // 	directionalLight.color.setHSL( 0.1, 1, 0.95 );
    // 	directionalLight.position.set( 0, 200, 0).normalize();
    // 	scene.add( directionalLight );
    //
    // 	var ambient = new THREE.AmbientLight( 0x404040 ); //AmbientLight,影响整个场景的光源
    // 	ambient.position.set(30,30,30);
    // 	scene.add( ambient );
    // }

    // 灯光
    function dolight(){
        // 平行光  模拟太阳光
        directionalLight = new DirectionalLight(0xffffff, 0.5);
        directionalLight.position.set(camera.position.x, camera.position.x,camera.position.z);
        let dhelper = new DirectionalLightHelper(directionalLight, 5, 0xff0000);
        // 光源直接放置于场景之上，光照颜色从天空光线颜色颜色渐变到地面光线颜色。
        let hemisphereLight = new HemisphereLight(0xffffff, 0xffffff, 0.4);
        hemisphereLight.position.set(0, 8, 0);

        scene.add(directionalLight);
        scene.add(hemisphereLight);
        // 光源开启阴影
        directionalLight.castShadow = true;
        directionalLight.shadow.mapSize = new THREE.Vector3(1024, 1024,1024);

    }

    // 坐标轴xyz  辅助器
    function doAxsHelper(){
        let axs  = new THREE.AxesHelper(10)
        scene.add(axs)
    }
    // 初始化实力
    function init() {
        dostats()

        const container = $(".Mbox");
     //   document.body.appendChild( container );
        labelRenderer = new CSS3DRenderer();
        labelRenderer.setSize( window.innerWidth, window.innerHeight );
        labelRenderer.domElement.style.position = 'absolute';
        labelRenderer.domElement.style.top = '0px';
        container.append( labelRenderer.domElement );



        camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        camera.position.set( -10, 8, 20);
        scene = new THREE.Scene();
        // scene.background=new THREE.Color("#cccccc")
        doWebGLRenderer()
        setOutLine()

        doloadGltfs()

        if(gltfurl=="lot9a.gltf"){

            gltfurl ="lot9a-paishui.gltf"
            doloadGltfs()

            gltfurl ="lot9a-tuanjian.gltf"
            doloadGltfs()



        }

        //全局部件颜色改为白色
        //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})


        // 模型Mesh开启阴影
        container.append( renderer.domElement)


       // container.appendChild( );


        doOrbiControls();

        container.append('<div style="background:red;height:100px;width:100px">erwer</div>')

        window.addEventListener( 'resize', onWindowResize, false );

        //
        // // 内存仪表盘
        // dostats()
        // // 创建画布
        // const container = document.createElement( 'div' );
        // document.body.appendChild( container );
        // // 透视摄像机
        // camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1,1000 );
        // camera.position.set(cameraPosition.x,cameraPosition.y,cameraPosition.z);
        // // 场景
        // scene = new THREE.Scene();
        // //全局部件颜色改为白色
        // //     scene.overrideMaterial= new THREE.MeshLambertMaterial({color:0xffffff})
        // let i = 0
        // // scene.background=new THREE.Color( "#353535" );
        // // 加载模型
        // doloadGltfs()
        // // 渲染器
        // doWebGLRenderer()
        // // 模型Mesh开启阴影
        // container.appendChild( renderer.domElement );
        // // 旋转控制
        // doOrbiControls()
        // // 开启页面点击监控

        // $(document).click(onDocumentMouseDown)
        // window.addEventListener( 'click', onDocumentMouseDown ); // use if there is no animation loop
        // // 页面缩小重置
        // window.addEventListener( 'resize', onWindowResize, false );

    }


    // 摄像头 旋转操控
    function doOrbiControls(){


        //
        // controls = new MapControls( camera, renderer.domElement );
        //
        // controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
        //
        // controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
        // controls.dampingFactor = 0.05;
        //
        // controls.screenSpacePanning = false;
        //
        // controls.minDistance = 100;
        // controls.maxDistance = 500;
        //
        // controls.maxPolarAngle = Math.PI / 2;
        // controls.update();
        //
        //
        controls = new OrbitControls( camera, labelRenderer.domElement );
        // controls.reset();
        controls.autoRotate = true;//是否自动旋转
        controls.autoRotateSpeed = 0.5;//自动旋转速度，正比

        controls.addEventListener( 'change', render ); // use if there is no animation loop
        controls.update()

    }

    // 渲染器
    function doWebGLRenderer(){
        renderer = new THREE.WebGLRenderer( { antialias: true } );
        renderer.setClearColor( 0xcccccc );

        renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( window.innerWidth, window.innerHeight );
        renderer.toneMapping = THREE.ACESFilmicToneMapping;
        renderer.toneMappingExposure = 1;
        renderer.outputEncoding = THREE.sRGBEncoding;

        renderer.physicallyCorrectLights = true;
        renderer.outputEncoding = THREE.sRGBEncoding;


        // 首先渲染器开启阴影
        renderer.shadowMap.enabled = true;


        // 环境光影响
        pmremGenerator = new PMREMGenerator(renderer );
        pmremGenerator.compileEquirectangularShader();
    }


    let axesDiv,axesScene,axesCamera,axesRenderer,axesCorner;
   function  addAxesHelper () {
        axesDiv = document.createElement('div');
        document.body.appendChild(axesDiv );
        axesDiv.classList.add('axes');

        const {clientWidth, clientHeight} = axesDiv;

         axesScene = new THREE.Scene();
        axesCamera = new THREE.PerspectiveCamera( 50, clientWidth / clientHeight, 0.1, 10 );
        axesScene.add( axesCamera );

        axesRenderer = new THREE.WebGLRenderer( { alpha: true } );
        axesRenderer.setPixelRatio( window.devicePixelRatio );
        axesRenderer.setSize( axesDiv.clientWidth,axesDiv.clientHeight );

        axesCamera.up =camera.up;
        axesCorner = new THREE.AxesHelper(5);
        axesScene.add( axesCorner );
        axesDiv.appendChild(axesRenderer.domElement);
    }


    // 后处理  选中部件加上外线
    function setOutLine(){
        composerAll = new EffectComposer( renderer );
        const renderPass = new RenderPass( scene, camera );
        composerAll.addPass( renderPass );

        outlinePass = new OutlinePass( new THREE.Vector2( window.innerWidth, window.innerHeight ), scene, camera );


        // edgeStrength: 3.0,  //强度 默认3
        //     edgeGlow: 1,    强度 默认1
        // edgeThickness: 1.0, //边缘浓度
        //     pulsePeriod: 0,  闪烁频率 默认0 值越大频率越低
        // usePatternTexture: false  使用纹理
        // visibleEdgeColor #ffffff 边缘可见部分发光颜色
        // hiddenEdgeColor #190a05  边缘遮挡部分发光颜色

        outlinePass.visibleEdgeColor.set('#fff'); // 选中颜色
        outlinePass.hiddenEdgeColor.set('#fff'); // 选中颜色
        // outlinePass.hiddenEdgeColor.set("#b33535");
        outlinePass.edgeStrength =5;
        outlinePass.edgeGlow =0.5;
        composerAll.addPass( outlinePass );

    }


    // 加载gltf 模型
    function  doloadGltfs(){
        $.dialog({
            id: 'loading',
            title: false,
            cancel: false,
            fixed: true,
            lock: true,
            resize: false,
        })
        try{
            let i = 0
            // scene.background=new THREE.Color( "#353535" );
            const loader = new GLTFLoader().setPath(gltfpath );
            loader.load( gltfurl, function ( gltf ) {
                console.log(gltf.scene)
                gltfobj=gltf
                console.log(gltf)
                gltf.scene.traverse( function ( child ) {
                    // console.log("33333333333333333333333")
                    // console.log(child)
                    // console.log(child.userData)
                    // console.log("name:"+child.name+"         uuuiiid"+child.userData.UniqueId)
                    // console.log("999999999999999999999999999999")
                    //
                    // if("f7d54af9-82bd-43de-9210-0e8af02555e6-000099e7"==child.uuid){
                    //     console.log("uuid:"+child.uuid)
                    //
                    // }
                    if ( child.isMesh ) {
                        child.material.emissive =  child.material.color;
                        child.material.emissiveMap = child.material.map ;
                        child.castShadow = true;
                        child.receiveShadow = true;
                    }



                } );




                doSetCameraPosition(gltf)
            } );



        }catch (e) {
            console.log("异常错误")
            console.log(e)
            $.dialog({id:'loading'}).close();

        }
    }



    let textGroup =[]
    // 根据模型位置设置  摄像头位置
    function doSetCameraPosition(gltf){
        // 重置镜头旋转
        // controls.reset();

        const box = new THREE.Box3().setFromObject(gltf.scene);
        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());


        console.log("sizeeeeeeeeeeeeeeeee")
        console.log(box)
        console.log(size)
        modelBox = box

        centetposition = center
        centetposition = center
        modelSize = size
       //  console.log("size===============")
       //  console.log(gltf)
       //  console.log(size)
       //  console.log(center)
       // let geometryx = new THREE.BoxGeometry(center.x+size/2, center.y+size/2, center.z+size/2); //宽，高，深
       //  let material = new THREE.MeshBasicMaterial({
       //      color: "#f60",
       //      wireframe: true
       //  }); //wireframe默认为false
       //  let cube = new THREE.Mesh(geometryx, material);
       //  scene.add(cube);


        modelX = box.max.x-box.min.x
        modelY = box.max.y-box.min.y
        modelZ = box.max.z-box.min.z


        const geometry = new THREE.BoxBufferGeometry(modelX, modelY, modelZ);
        const edges = new THREE.EdgesGeometry( geometry );
        const line = new THREE.LineSegments( edges, new THREE.MeshBasicMaterial( { color: 0xffffff } ) );
        let xase3=  new THREE.BoxHelper( line )
        scene.add(xase3 );

        console.log("line.position")
        console.log(xase3.position)

        let mt = new THREE.Vector3(box.min.x,box.min.y,box.min.z)

        //
        //
        // const cp = new THREE.BufferGeometry();
        // cp.setFromObject(gltf.scene)
        // // // // 单构件加外边框   包围盒  start
        // // // let mqs = gltf.scene.clone()
        // // // // mqs.rotation.x+=4.7
        // // // let cp = mqs.geometry
        // let taup = 900
        // //
        // console.log(cp.boundingBox)
        //  console.log("xxxxxxxxxxxxxxxxxxxxx")
        //  console.log("xxxxxxxxxxxxxxxxxxxxx")
        //
        // var object = new THREE.Mesh(cp, new THREE.MeshBasicMaterial(0xff0000));
        // let   boxx= new THREE.BoxHelper(object, 0xffff00);
        // scene.add(boxx);
        // // 单构件加外边框   包围盒  end
        // // 旋转重置


        let cc =new THREE.Vector3()
        //
        // let location =   center.clone()
        //
        // let location2 = center.clone()
        // let location3 =  center.clone()
        // //


        gltf.scene.position.x += (gltf.scene.position.x - center.x);
        gltf.scene.position.y += (gltf.scene.position.y - center.y);
        gltf.scene.position.z += (gltf.scene.position.z - center.z);


        controls.maxDistance = size * 100;
        camera.near = size / 100;
        camera.far = size * 100;

        camera.position.copy(center);
        camera.position.x += size*2;
        camera.position.y +=  size*2;
        camera.position.z +=  size*2;;
        // console.log(camera.position)

        //
        // camera.position.x += size;
        // camera.position.y += size;
        // camera.position.z += size;
        console.log("cccccccccccc")
        console.log(center)

        console.log("cccccccccccc22222222")

        camera.lookAt(center);
        camera.updateProjectionMatrix();
        // gltf.scene.rotation.x=4.7
        controls.update()

        scene.add( gltf.scene );
        $.dialog({id:'loading'}).close();

        let location =  box.min.clone()

        let location2 = box.min.clone()
        let location3 = box.min.clone()



        modelX = box.max.x-box.min.x
        modelY = box.max.y-box.min.y
        modelZ = box.max.z-box.min.z

        location.x= box.min.x

        dotxt("X:"+modelX+"mm ",location)


       //  location2.y= box.min.y
        dotxt("y:"+modelY+"mm",location2);
        location3.z=box.min.z
        dotxt("z:"+modelZ+"mm",location3);


        dobujian(gltf)

        initText("dfgdfgdfg電飯鍋電飯鍋電飯鍋電飯鍋個",location)
        function initText( wordFont, p1){

            var particleMaterial = new THREE.SpriteMaterial( {

                color: 0x000000,
                program: function ( context ) {

                    context.beginPath();
                    context.font="bold 2000000px Arial";
                    context.fillStyle="#058";
                    context.transform(-1,0,0,1,0,0);
                    context.rotate(Math.PI);
                    context.fillText( wordFont , 0, 0 );

                }

            } );


            var particle = new THREE.Sprite( particleMaterial );
            particle.position.copy( p1 );
            particle.rotation.x = Math.PI/2;
            //      particle.lookAt( camera );
            scene.add( particle );

            //            var textGeometry = new THREE.TextGeometry(wordFont,{
            //                "font": font,
            //                "size" : 10,
            //                "height" : 0,
            //                "color" : 0x000000
            //            })
            //
            //            var text = new THREE.Mesh( textGeometry, new THREE.MeshBasicMaterial( { color: 0x000000 } ) );
            //
            //
            //            text.position.x = p1.x + 2;
            //            text.position.y = p1.y + 2;
            //            text.position.z = p1.z + 2;
            //            text.lookAt(camera.position);
            //            scene.add(text);

        }



        function dotxt(str,location){
            const earthDiv = document.createElement( 'div' );
            earthDiv.className = 'label';
            earthDiv.textContent = str;

            earthDiv.style.fontSize = '111em';
            earthDiv.style.marginTop = '0em';

            earthDiv.style.color = '#f60';
            const earthLabel = new CSS3DObject( earthDiv );
            earthLabel.position .copy(location)
          //  earthLabel.position .copy(location)
            console.log(333333333)
            const geometryx = new THREE.BoxBufferGeometry(11110, 11110, 11110 );
            const materialx = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
            const meshx = new THREE.Mesh( geometryx, materialx );
            meshx.position .copy(location)

            console.log("xxxxxxxxxxxxxxxx")
            console.log(earthLabel)
            console.log(location)
          //  meshx.add( earthLabel );
         //   scene.add( meshx );
            textGroup.push(earthLabel)
            scene.add( earthLabel );
        }



        render()

    }







    function onWindowResize() {



        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
        render();
    }


    var projector =new THREE.Raycaster()
    function onDocumentMouseDown(event){

        console.log(3333333333333)
        return
        let objectss =[]
        let mouse = new THREE.Vector2();
        console.log(scene)
        //将鼠标点击位置的屏幕坐标转成threejs中的标准坐标,具体解释见代码释义
        let x = (event.clientX / window.innerWidth) * 2 - 1;
        let y = -(event.clientY / window.innerHeight) * 2 + 1;
        //新建一个三维单位向量 假设z方向就是0.5
        //根据照相机，把这个向量转换到视点坐标系
        var vector = new THREE.Vector3(x, y,0.5).unproject(camera);

        //在视点坐标系中形成射线,射线的起点向量是照相机， 射线的方向向量是照相机到点击的点，这个向量应该归一标准化。
        var raycaster = new THREE.Raycaster(mouse, camera);


        scene.group.forEach(child=>{
            console.log(child)
            if(child in THREE.Mesh){
                objectss.push(child)
            }
        })

        //射线和模型求交，选中一系列直线
        var intersects = raycaster.intersectObjects( objectss);
        console.log('imtersrcts=' + intersects)
        if (intersects.length > 0) {
            //选中第一个射线相交的物体
            let  SELECTED = intersects[0].object;
            var intersected = intersects[0].object;
            console.log(intersects[0].object)
        }
    }


    function createShaderMaterial( shader) {

        const u = THREE.UniformsUtils.clone( shader.uniforms );

        const vs = shader.vertexShader;
        const fs = shader.fragmentShader;

        const material = new THREE.ShaderMaterial( { uniforms: u, vertexShader: vs, fragmentShader: fs } );


        return material;

    }
    function guanghui(){

        let composer = new EffectComposer(renderer)
        let renderPass = new RenderPass(scene, camera);
        composer.addPass(renderPass);

        let outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, camera);
        composer.addPass(outlinePass);

        outlinePass.visibleEdgeColor.set('#130AF2'); // 选中颜色
        outlinePass.edgeStrength = 5;
        outlinePass.edgeGlow = 1.5;
        const render = function () {
            console.log(333333333333333)

            composer.render();
        }


    }


    function dodiban(){
        let floorGeometry = new PlaneGeometry(1000, 1000, 1);
        let floorMaterial = new MeshPhongMaterial({
            color: 0x77F28F,
            //   color:  colorArr[colorIndex],
            shininess: 0,
            // wireframe: true
        });
        floor = new Mesh(floorGeometry, floorMaterial);
        floor.rotation.x = -0.5 * Math.PI;
        floor.position.y = -2.1;

        // 地板接受阴影开启
        floor.receiveShadow = true;
        scene.add(floor);
    }


    // 点击部件
    function  dobujian(gltf){
        console.log("点击部件")
        let raycaster = new THREE.Raycaster();
        let mouse = new THREE.Vector2();
        const selectHandler = function (ev) {

            if(ev.clientX==undefined){
                ev.clientX =ev.originalEvent.changedTouches[0].clientX
            }
            if(ev.clientY==undefined){
                ev.clientY =ev.originalEvent.changedTouches[0].clientY
            }
            // mouse.x = (ev.clientX / window.innerWidth) ;
            // mouse.y = -(ev.clientY / window.innerHeight);

            mouse.x = (ev.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(ev.clientY / window.innerHeight) * 2 + 1;
            raycaster.setFromCamera(mouse, camera);
            // 这里我们只检测模型的选中情况
            let intersects = raycaster.intersectObjects(gltf.scene.children, true);
            if (intersects.length > 0) {
                //   console.log(intersects)
                let selectedObjects = intersects[0].object;

                changecolor(selectedObjects)
                //
                // for ( let i = 0; i < intersects.length; i ++ ) {
                //    // intersects[ i ].object.material.color.set( 0xff0000 );
                // }

            }
        }


        if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i))) {
            console.log("手机访问111111111.");
            $(document).on('click touchend',function(e){
                selectHandler(e)
                console.log("2222222222xxxxxxxxxxx")
                //  location.href = $(this).attr('data-url');
                //  return false;
            });
        }else{
            document.body.addEventListener('click', selectHandler, false);

            console.log("电脑访问111111111.");
        }



        //  document.body.addEventListener('click', selectHandler, false);
    }


    function resizeSelectHandle(){

    }

    function addSelectedObject( object ) {

        selectedObjects = [];
        selectedObjects.push( object );

    }


    function initObject (x,y,z) {
        let  geometry = new THREE.Geometry();
        console.log(scene.position)
        console.log(camera.position)
        geometry.vertices.push(
            new THREE.Vector3(camera.position.x-100, camera.position.y, camera.position.z-100),
            new THREE.Vector3(camera.position.x-100, camera.position.y-10, camera.position.z),


            new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z-200),
            new THREE.Vector3(camera.position.x, camera.position.y-20, camera.position.z-200),
            new THREE.Vector3(camera.position.x, camera.position.y-30, camera.position.z-200),
        );
        geometry.colors.push(
            new THREE.Color(0x444444),
            new THREE.Color(0xFF0000)
        )
        let  material = new THREE.LineBasicMaterial({vertexColors: true});
        var line = new THREE.Line(geometry, material);
        scene.add(line);
    }


   function changecolor(selectedObjects){
        let newMaterial = selectedObjects.material.clone();

        let oldMaterialObj  = selectedObjects.material.clone();


        const box = new THREE.Box3().setFromObject(selectedObjects);
        const boxxx = box.getSize();

        const size = box.getSize(new THREE.Vector3()).length();
        const center = box.getCenter(new THREE.Vector3());

        let    sphere = new THREE.SphereGeometry(3.5);

        console.log(33333333333111111111333333331)


        // // 单构件加外边框   包围盒  start
        // let mqs = selectedObjects.clone()
        // // mqs.rotation.x+=4.7
        // let cp = mqs.geometry
        // let taup = 900
        // cp.boundingBox.min.x=cp.boundingBox.min.x-taup
        // cp.boundingBox.min.y=cp.boundingBox.min.y-taup
        // cp.boundingBox.min.z=cp.boundingBox.min.z-taup
        // cp.boundingBox.max.x=cp.boundingBox.max.x+taup
        // cp.boundingBox.max.y=cp.boundingBox.max.y+taup
        // cp.boundingBox.max.z=cp.boundingBox.max.z+taup
        // console.log(cp)
        // var object = new THREE.Mesh(cp, new THREE.MeshBasicMaterial(0xff0000));
        // let   boxx= new THREE.BoxHelper(object, 0xffff00);
        // scene.add(boxx);
        // // 单构件加外边框   包围盒  end

        console.log("objectName")
        console.log("box")
        console.log(box)
        console.log("size")
        console.log(size)
        console.log("center")
        console.log(center)

        let v = new THREE.Vector3()
        // console.log(selectedObjects.position)
        //
        // // 创建动画
        // // let component = gltf.scene.getObjectByName('car_body');
        // TweenLite.to(selectedObjects.position,5, {
        //     y: 50,
        //     x:500,
        //     ease: Bounce.easeOut
        // });


        let selectedObjectsx = [];
        selectedObjectsx.push( selectedObjects );
        outlinePass.selectedObjects = selectedObjectsx

        let color = newMaterial.color
        if(oldSelect && oldMaterial){
            if(oldSelect.uuid == selectedObjects.uuid){
                newMaterial = oldMaterial
                //     newMaterial.color
                oldMaterial = ''
                oldSelect = ''
            }else{
                oldSelect.material = oldMaterial
                oldMaterial = ''
                oldSelect = ''
                oldSelect =  selectedObjects
                oldMaterial = oldMaterialObj
                newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
            }

        }else{
            oldSelect =  selectedObjects
            oldMaterial = oldMaterialObj
            newMaterial.color =  new THREE.Color(colorArr[colorIndex]); //重新修改颜色
        }

        let  uuidKey = selectedObjects.userData.UniqueId


        let html = "<div class='tableTop'>\n"


        html+="    <div class='table border'>\n" +
            "        <div class='text-right dleft border'>name:</div>\n" +
            "        <div class='text-left dright'>"+selectedObjects.name+"</div>\n" +
            "    </div>\n"
        //
        // html+="    <div class='table border'>\n" +
        //     "        <div class='text-right dleft border'>uuid:</div>\n" +
        //     "        <div class='text-left dright'>"+selectedObjects.uuid+"</div>\n" +
        //     "    </div>\n"
        if(jsondata[uuidKey]){

            let danwei = "M"
            let rows = jsondata[uuidKey]
            //
            // html+="    <div class='table border'>\n" +
            //     "        <div class='text-right dleft border'>项目名称:</div>\n" +
            //     "        <div class='text-left dright'>"+rows.ProjectName+"</div>\n" +
            //     "    </div>\n"

            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>类型:</div>\n" +
                "        <div class='text-left dright'>"+rows.Type+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>长:</div>\n" +
                "        <div class='text-left dright'>"+rows.Length+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>宽:</div>\n" +
                "        <div class='text-left dright'>"+rows.Width+danwei+"</div>\n" +
                "    </div>\n"


            html+="    <div class='table border'>\n" +
                "        <div class='text-right dleft border'>厚/高:</div>\n" +
                "        <div class='text-left dright'>"+rows.Height+danwei+"</div>\n" +
                "    </div>\n"


        }

        html+="</div>"
        $.dialog({id:'testID2'}).close();
        $.dialog({
            top:"100%",
            title: "构件信息",
            width:"100%",
            id: 'testID2',
            content: html
        });
       // selectedObjects.material = newMaterial;
        render()
    }
    createGUI()
    // 创建ui界面
    function createGUI() {
        return

        if ( gui ) gui.destroy();

        gui = new GUI( { width: 400 } );

        // SHADOW


        let  guiData={
            drawStrokes:true,
            drawFillShapes:4,
            strokesWireframe:true,
            fillShapesWireframe:true,
        }



        gui = new GUI( { width: 350 } );
        gui.addFolder( "Shadow" );

        gui.add( guiData, 'drawStrokes' ).name( 'Draw strokes' ).onChange( update );

        gui.add( guiData, 'drawFillShapes',1,100 ).name( 'Draw fill shapes' ).onChange( update );

        gui.add( guiData, 'strokesWireframe' ).name( 'Wireframe strokes' ).onChange( update );

        gui.add( guiData, 'fillShapesWireframe' ).name( 'Wireframe fill shapes' ).onChange( update );


        function update() {

        }

    }


    //清理效果
    function cleaningEffect(){


    }


    //内存  帧数 仪表
    function dostats(){
        stats = new Stats();
        $("#stat").html( stats.dom)

    }

    function changexxx(){
       console.log("changexxxchangexxxchangexxxchangexxxchangexxxchangexxxchangexxx")
       for (let i=0;i<textGroup.length;i++){
          textGroup[i].rotation.copy(camera.rotation)
          // planeGroup[i].rotation.copy(camera.rotation)
       }
    }

    function render() {

       console.log("cccccccccccccccccddddddeeeeeeeeeee")
       console.log(centetposition)

        if(labelRenderer){
            
            labelRenderer.render( scene, camera );
        }
        composerAll.render()
        stats.update()

    }



</script>



<script>
    $(function(){
        let h  =$(window).height()
        $(".box").height(h)
        $(".left a ").eq(1).addClass("hover")
        $(".left a ").click(function(){
            $(".left a ").removeClass("hover")
            $(this).addClass("hover")

        })
    })

</script>
<style>
    .label {
        /*margin-top: -20px;*/
        color: #fff;
        padding: 3px 5px;
        background:#FFF1B8
    }
</style>
</body>
</html>
